package com.stox.client.ui.javafx.watchlist.view;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;

import com.stox.client.api.core.ClientFactory;
import com.stox.client.api.watchlist.WatchlistClient;
import com.stox.client.ui.javafx.watchlist.widget.WatchlistComboBox;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.i18n.MessageSource;
import com.stox.shared.model.Watchlist;

public class EditWatchlistConfigurationView extends BorderPane implements EventHandler<ActionEvent>{
	
	private Watchlist watchlist;
	private final WatchlistComboBox watchlistComboBox;
	private final TextField textField = new TextField();
	
	public EditWatchlistConfigurationView(WatchlistComboBox watchlistComboBox) {
		this.watchlistComboBox = watchlistComboBox;
		this.watchlist = watchlistComboBox.getValue();
		
		UI.style(this, CSS.watchlistConfigurationView);
		UI.style(textField, CSS.undecorated);
		
		textField.setPromptText(MessageSource.get("Enter.Watchlist.Name"));
		setTop(textField);
		
		populateView();
	}

	protected void populateView(){
		textField.setText(watchlist.getName());
	}
	
	protected void populateModel(){
		watchlist.setName(textField.getText());
	}
	
	protected void updateWatchlistComboBox(){
		watchlistComboBox.getItems().set(watchlistComboBox.getItems().indexOf(watchlist), watchlist);
		watchlistComboBox.getSelectionModel().select(watchlist);
	}
	
	@Override
	public void handle(ActionEvent event) {
		populateModel();
		watchlist.setId(ClientFactory.getClient(WatchlistClient.class).saveOrUpdate(watchlist));
		updateWatchlistComboBox();
	}

	public Watchlist getWatchlist() {
		return watchlist;
	}

	public void setWatchlist(Watchlist watchlist) {
		this.watchlist = watchlist;
	}

	public WatchlistComboBox getWatchlistComboBox() {
		return watchlistComboBox;
	}

	public TextField getTextField() {
		return textField;
	}
}
